package com.angel.activity;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.angel.entity.ActivityBeanList;
import com.angel.entity.Task;
import com.angel.port.IActivity;
import com.angel.service.TaskService;
import com.angel.util.BaseUtil;
import com.angel.util.ConstUtil;
import com.angel.util.HttpUtil;
import com.angel.util.NetUtil;
import com.angel.util.StringUtil;
import com.angel.util.UserInfoUtil;
import com.google.gson.reflect.TypeToken;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.umeng.analytics.MobclickAgent;
import com.weibo.net.AccessToken;
import com.weibo.net.AsyncWeiboRunner;
import com.weibo.net.AsyncWeiboRunner.RequestListener;
import com.weibo.net.DialogError;
import com.weibo.net.Weibo;
import com.weibo.net.WeiboDialogListener;
import com.weibo.net.WeiboException;
import com.weibo.net.WeiboParameters;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;

public class LoginActivity extends Activity implements RequestListener,IActivity{
	/**
	 * @author ming 
	 */
	private Button loginButton;
	private Button createButton;
	private Button weiboBtn,qqBtn;
	private EditText acountEdit,passwordEdit;
	private String acountTxt,passwordTxt="";
	private Context context;
	private String getAccount,qqAccount,weiBoAccount;
	private String getPassword;
	private HashMap<String,String> map=new HashMap<String,String>();
	private HashMap<String,String> hashmap=new HashMap<String,String>(2);
	private Intent intent;
	private ButtonActionListener listener;
	private Tencent mTencent;
    private  ActivityBeanList activityBeanList;
    private ProgressDialog progressDialog;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		 MobclickAgent.onError(this);//自动捕获异常退出（FC ）
//		setContentView(R.layout.login);
		context=LoginActivity.this;
		 progressDialog=new ProgressDialog(context);
		 getAccount=UserInfoUtil.getValue(context, "phoneAccount","");
	     getPassword=UserInfoUtil.getValue(context, "password","");
	     qqAccount=UserInfoUtil.getValue(context, "openid","");
	     weiBoAccount=UserInfoUtil.getValue(context, "uid","");
	 	Log.i("LoginActivity","LoginActivity-->onCreate"+getAccount+"password:"+getPassword+"qq:"+qqAccount);
	   
	 	if(NetUtil.checkNetState(context)){//当网络连接正常
	 		 if(!getAccount.equals("")&&!getPassword.equals("")) /*手机号不为空,则直接登陆*/
	 	    {  
	 		    	map.put("account", getAccount);
	 				map.put("password", getPassword);
	 				map.put("loginMethod", "1");
	 		    	BaseUtil.startService(Task.LOGIN_ACTIVITY,this,map);//启动登陆
	 		    	progressDialog.setMessage("登陆中...");
	 		    	progressDialog.show();
	 		    	/*添加全局变量，标志是通过手机号登陆的*/
	 		    	hashmap.put("isAccountLogin", "1");
	 		    	UserInfoUtil.setValue(context, hashmap);
	 		    	Log.i("LoginActivity","login by phone"+"account:"+getAccount+"paw:"+getPassword);
	 	    
	 	    }else if(!weiBoAccount.equals("")){//判断微博账号是否为空
	 	    		map.put("account", weiBoAccount);
	 		    	map.put("loginMethod", "2");
	 		    	map.put("userName", UserInfoUtil.getValue(context, "userName",""));
	 		    	progressDialog.setMessage("登陆中...");
	 		    	progressDialog.show();
	 		    	BaseUtil.startService(Task.LOGIN_ACTIVITY,this,map);//启动登陆
	 		    	Log.i("LoginActivity","login by weibo:"+weiBoAccount);
	 	    	
	 	    }else if(!qqAccount.equals("")){//判断qq账号是否为空
	 	    	map.put("userName", UserInfoUtil.getValue(context, "userName","qq匿名"));
	 	    	map.put("account", qqAccount);
	 	    	map.put("loginMethod", "3");
	 	    	progressDialog.setMessage("登陆中...");
	 	    	progressDialog.show();
	 	    	BaseUtil.startService(Task.LOGIN_ACTIVITY,this,map);//启动登陆
	 	    	Log.i("LoginActivity","login by qqAccount:"+qqAccount);
	 //	    	finish();
	 	    }
	 	    else{  //之前没绑定账号，执行登陆界面布局
	 			setContentView(R.layout.login);
	 			setView();
	 		}
	 	}else{//网络连接异常
	 		BaseUtil.makeToast(this, "请检查您的网络连接");
    		finish();
	 	}
	 	//保存设备dpi类型
		UserInfoUtil.setValue(context,"DpiType", BaseUtil.getDpiType(this));
	}
	
	/*获取布局*/
	public void setView(){
		loginButton = (Button) findViewById(R.id.login_btn);
		createButton = (Button)findViewById(R.id.create_Account);
		weiboBtn = (Button)findViewById(R.id.weibo_account_login);
		qqBtn=(Button)findViewById(R.id.qq_account_login);
		listener=new ButtonActionListener();
		loginButton.setOnClickListener(listener);
		createButton.setOnClickListener(listener);
		weiboBtn.setOnClickListener(listener);
		qqBtn.setOnClickListener(listener);
		
		acountEdit=(EditText)findViewById(R.id.login_userName);
		passwordEdit=(EditText)findViewById(R.id.login_password);	
	}
	private class ButtonActionListener implements OnClickListener {
		public void onClick(View v) {
			int id=v.getId();
		    if(id== R.id.login_btn){
		    	MobclickAgent.onEvent(LoginActivity.this, "phoneLogin");//友盟记录用手机号登陆
				acountTxt=acountEdit.getText().toString();
				passwordTxt=passwordEdit.getText().toString();
				
				if(StringUtil.isBlank(acountTxt)||StringUtil.isBlank(passwordTxt)){
					BaseUtil.makeToast(LoginActivity.this, "请输入账号或密码");
				}else{//启动登陆
					MobclickAgent.onEvent(LoginActivity.this, "phoneLogin");//友盟记录用手机登陆
					map.put("account", acountTxt);
					map.put("password", passwordTxt);
					map.put("loginMethod", "1");
					map.put("userName", "abc");
					loginToMain(map);
					/*添加全局变量，标志是通过手机号登陆的*/
			    	hashmap.put("isAccountLogin", "1");
			    	UserInfoUtil.setValue(context, hashmap);
				}
		    }else if(id==R.id.create_Account){
				intent = new Intent();
				intent.setClass(LoginActivity.this, Register1Activity.class);
				intent.putExtra("isBind", "0");
				startActivity(intent);
		    }else if(id==R.id.weibo_account_login){
		    	if(!UserInfoUtil.judgeOauth(context,"weibo_access_token") ){//若未授权，执行下面操作
					UserInfoUtil.oauthRequest(context,new AuthListener());
				}
				else{
					weiboLogin();
				}
		    }else if(id==R.id.qq_account_login){
		    	mTencent = Tencent.createInstance(ConstUtil.APP_ID, context.getApplicationContext());
		    	mTencent.login(LoginActivity.this, ConstUtil.SCOPE, new MyIUiListener());
		    	MobclickAgent.onEvent(LoginActivity.this, "QQLogin");//友盟记录用QQ登陆
		    }
		}

	}
	/*用于qq登录*/
	public void qqLogin(){
//		 String openId=UserInfoUtil.getValue(this, "openid", "0");
//		 String result=null;
//		 String openid=UserInfoUtil.getValue(context, "openid", "");
//		 String access_token=UserInfoUtil.getValue(context, "access_token", "");
//		 String userInfoUrl="https://graph.qq.com/user/get_user_info?access_token="+access_token+"&oauth_consumer_key="+ConstUtil.APP_ID+"&openid="+openid;
//		 result=HttpUtil.httpGet(userInfoUrl);
		 JSONObject obj;
//					obj = new JSONObject(result);
//					String screen_name=obj.getString("nickname");
					Log.i("LoginActivity","LoginActivity-->"+"匿名");
//					SharedPreferences.Editor editor=context.getSharedPreferences(UserInfoUtil.USER_TABLE,Context. MODE_WORLD_WRITEABLE).edit();
//					editor.putString("userName", "匿名");//存储用户名称
//					editor.commit();
					//微博登陆到主推活动
					map.put("account", UserInfoUtil.getValue(context, "openid", ""));
					map.put("password", UserInfoUtil.getValue(context, "password", ""));
					map.put("loginMethod", "3");
					map.put("userName", "匿名");
					loginToMain(map);//跳转登陆
					
					/*添加全局变量，标志是通过qq登陆的*/
			    	hashmap.put("isAccountLogin", "3");
			    	UserInfoUtil.setValue(context, hashmap);
					
	}
	/*封装请求参数及跳转登陆*/
	public void loginToMain(HashMap<String,String> map){
		progressDialog.setMessage("登陆中...");
		progressDialog.show();
		//启动后台服务器
		BaseUtil.startService(Task.LOGIN_ACTIVITY, this, map);
	}
	
	/**
	 * 微博请求登录 
	 */
	public void weiboLogin(){
		 String uid=UserInfoUtil.getValue(this, "uid", "0");
		 String result=null;
		 SharedPreferences pre=getSharedPreferences(UserInfoUtil.USER_TABLE,Context. MODE_WORLD_WRITEABLE);
		 Weibo weibo=Weibo.getInstance();
		 //从存储中获取access_token
	     String access_token=pre.getString("weibo_access_token", "");
		   //获得token对象
		   AccessToken token=new AccessToken(access_token,Weibo.getAppSecret());
		   weibo.setAccessToken(token);
		 try {
			result=getWeiboUserInfo(weibo.getAppKey(),access_token,uid);
			if(result!=null){//若结果不为null
				JSONObject obj=new JSONObject(result);
				String screen_name=obj.getString("screen_name");
				Log.i("LoginActivity","LoginActivity-->"+screen_name);
				SharedPreferences.Editor editor=context.getSharedPreferences(UserInfoUtil.USER_TABLE,Context. MODE_WORLD_WRITEABLE).edit();
				editor.putString("userName", screen_name);//存储用户名称
				editor.commit();
				//微博登陆到主推活动
				map.put("account", UserInfoUtil.getValue(context, "uid", ""));
				map.put("password", UserInfoUtil.getValue(context, "password", ""));
				map.put("loginMethod", "2");
				map.put("userName", screen_name);
				loginToMain(map);//跳转登陆
			}
		} catch (WeiboException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	/*微博请求用户信息*/
	public String getWeiboUserInfo(String source,String access_token,String uid) throws WeiboException{
		String userUrl="https://api.weibo.com/2/users/show.json";
		Weibo weiBo=Weibo.getInstance();
		WeiboParameters params=new WeiboParameters();
		params.add("source", source);
		params.add("access_token", access_token);
		params.add("uid", uid);
		String result=weiBo.request(context, userUrl, params, "GET",weiBo.getAccessToken());
		return result;
	}
	//忘记密码按钮
    public void login_pw(View v) {     
//    	Uri uri = Uri.parse("http://3g.qq.com"); 
    	Intent intent = new Intent(LoginActivity.this,Register1Activity.class); 
    	intent.putExtra("isBind", "2");//表示找回密码
    	startActivity(intent);
      }

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode==KeyEvent.KEYCODE_BACK){
			//QuitProgress.EXIT_PROGRESS
			BaseUtil.showExitDialog(this);
		}
		return super.onKeyDown(keyCode, event);
	}  
	/*微博登陆页面回调*/
	class AuthListener  implements WeiboDialogListener {
		@Override
		public void onComplete(Bundle values) {
			String token = values.getString("access_token");
			String expires_in = values.getString("expires_in");
			String uid=	 values.getString("uid");
			
			AccessToken accessToken = new AccessToken(token, Weibo.getAppSecret());
			accessToken.setExpiresIn(expires_in);
			/*通过Preference用于存储获取到的access_token,access_token_secret*/
			SharedPreferences.Editor editor=context.getSharedPreferences(UserInfoUtil.USER_TABLE,Context. MODE_WORLD_WRITEABLE).edit();
			/*获取当前系统时间*/
			long oauthTime=BaseUtil.getTime();
			editor.putString("uid", uid);
			editor.putString("weibo_access_token", token);
			editor.putString("access_token_secret", accessToken.getSecret());
			editor.putString("weibo_expire_in", expires_in);//存储离过期的时间
			editor.putLong("oauthTime", oauthTime);//保存当前时间
			
			editor.commit();//注意:应该进行保存
			Weibo.getInstance().setAccessToken(accessToken);
			weiboLogin();
			Log.i("TAG", "Thread -->name:"+Thread.currentThread().getName()+"   id:"+Thread.currentThread().getId());
			MobclickAgent.onEvent(LoginActivity.this, "weiboLogin");//友盟监听用微博成功登陆事件
			
			/*添加全局变量，标志是通过微博号登陆的*/
	    	hashmap.put("isAccountLogin", "2");
	    	UserInfoUtil.setValue(context, hashmap);
		}
		@Override
		public void onWeiboException(WeiboException e) {
			BaseUtil.makeToast(LoginActivity.this, "Auth exception : " + e.getMessage()+"status code"+e.getStatusCode());
			Log.i("LoginActivity","Auth exception : " + e.getMessage()+"status code"+e.getStatusCode());
		}

		@Override
		public void onError(DialogError e) {
			BaseUtil.makeToast(LoginActivity.this, "认证出现错误 : " + e.getMessage()+"status code");
		}

		@Override
		public void onCancel() {
			BaseUtil.makeToast(LoginActivity.this, "认证取消");
		}
	}
	@Override
	public void onComplete(String response) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onIOException(IOException e) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onError(WeiboException e) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void init() {
	}
	@Override
	public void refresh(Object... params) {
		 String isSucess=BaseUtil.getValueFromJSON((String)params[0]);
		
		 if(isSucess.equals("2")){
			 BaseUtil.makeToast(LoginActivity.this, "对不起,网络连接超时,请稍后重试...");
			 progressDialog.dismiss();
			 UserInfoUtil.clearUserMsg(context);
			 TaskService.removeActivity(LoginActivity.this);
			 finish();
			 startActivity(new Intent(this,LoginActivity.class));
			 return ;
		}
		/*跳转到主推活动*/
		 Type type=new TypeToken<ActivityBeanList>(){}.getType();
		 activityBeanList=(ActivityBeanList)BaseUtil.getEntityFromJson((String)params[0],type);
		 if(isSucess.equals("0")){//如果登录不成功
			 BaseUtil.makeToast(LoginActivity.this, "对不起，您的账号或密码错误，请重新输入");
		 }else{//如果登录成功，则将数据传递到下个Activity
			    /*保存账号密码,如果不是用手机号登陆，就为空字符串*/
			    HashMap<String,String> hashMap=new HashMap<String,String>();
				    hashMap.put("phoneAccount", activityBeanList.getTelNum());
				    if(!passwordTxt.equals("")){//若密码不为空字符，则保存
					hashMap.put("password", passwordTxt);}
					hashMap.put("email", activityBeanList.getEmail());
					hashMap.put("openid", activityBeanList.getQq());
					hashMap.put("uid", activityBeanList.getWeibo());
					hashMap.put("userId",activityBeanList.getUserId());
					hashMap.put("userName",activityBeanList.getUserName());
				UserInfoUtil.setValue(context, hashMap);
				/*跳转到Tab上的Activity*/
				intent = new Intent();
				intent.setClass(LoginActivity.this, BottomMeunTab.class);
				intent.putExtra("jsonData",(String)params[0]);
				startActivity(intent);
		 }
		 progressDialog.cancel();
	}
	
	/**
	 * qq登陆页面回调
	 *
	 */
	class MyIUiListener implements  IUiListener {
		@Override
		public void onCancel() {
		}
		@Override
		public void onComplete(JSONObject arg0) {
			try {
				String openid = arg0.getString("openid");
				String access_token=arg0.getString("access_token");
				String expires_in=arg0.getString("expires_in");
				long expiresIn= System.currentTimeMillis() + Long.parseLong(expires_in) * 1000;
				SharedPreferences.Editor editor=context.getSharedPreferences(UserInfoUtil.USER_TABLE,Context. MODE_WORLD_WRITEABLE).edit();
				editor.putString("openid", openid);
				editor.putString("qq_access_token", access_token);
				editor.putLong("qq_expires_in",expiresIn);
				editor.commit();
				mTencent.setAccessToken(access_token, expiresIn+"");
				qqLogin();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		@Override
		public void onError(UiError arg0) {
			BaseUtil.makeToast(LoginActivity.this, "error code:"+arg0.errorCode);
		}
	}
	@Override
	protected void onStart() {
		super.onStart();
		Log.i("LoginActivity","LoginActivity-->onStart");
	}

	@Override
	protected void onResume() {
		super.onResume();
		Log.i("LoginActivity","LoginActivity-->onResume");
		MobclickAgent.onResume(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		Log.i("LoginActivity","LoginActivity-->onPause");
		MobclickAgent.onResume(this);
		
	}

	@Override
	protected void onStop() {
		super.onStop();
		Log.i("LoginActivity","LoginActivity-->onStop");
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		Log.i("LoginActivity","LoginActivity-->onDestroy");
	}
}
